package com.gree.elasticsearch.security.filter;

import com.frameworkset.util.StringUtil;
import com.gree.elasticsearch.security.JwtAuthenticationToken;
import com.gree.elasticsearch.security.exception.JwtEmptyException;
import com.gree.elasticsearch.security.requestmatcher.SkipRequestMatcher;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 总有刁民想害朕，请叫我小花狗
 * create by zxw on 2020/5/30
 */
public class JwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class.getName());

    private AuthenticationFailureHandler authenticationFailureHandler;

    private RequestMatcher requestMatcher;

    public JwtAuthenticationFilter(AuthenticationFailureHandler authenticationFailureHandler, RequestMatcher requestMatcher) {
        super(new AntPathRequestMatcher("/api/**"));
        this.authenticationFailureHandler = authenticationFailureHandler;
    }

    public JwtAuthenticationFilter(String defaultFilterProcessesUrl) {
        super(defaultFilterProcessesUrl);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {

        String bearToken = request.getHeader("authorization");
        if (StringUtils.isEmpty(bearToken)) throw new JwtEmptyException();

        logger.debug("jwt authentication filter execute receive a need been authenticated request. bearToken is {}", bearToken);

        JwtAuthenticationToken jwtAuthenticationToken = new JwtAuthenticationToken(bearToken);

        return this.getAuthenticationManager().authenticate(jwtAuthenticationToken);
    }

    @Override
    public void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                                                   FilterChain filterChain, Authentication authenticationResult) throws IOException, ServletException {
        logger.debug("jwt authentication filter authentication success.");
        SecurityContextHolder.getContext().setAuthentication(authenticationResult);
        filterChain.doFilter(request, response);
    }

    @Override
    public void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException {
        // 清空保存在SecurityContext中的信息
        SecurityContextHolder.clearContext();
        authenticationFailureHandler.onAuthenticationFailure(request, response, authenticationException);
    }
}
